package com.ecut.drug_bid.service;

import com.ecut.drug_bid.domain.User;
import com.ecut.drug_bid.domain.UserType;
import com.ecut.drug_bid.dto.AuthResponse;
import com.ecut.drug_bid.dto.LoginRequest;
import com.ecut.drug_bid.dto.RegisterRequest;
import com.ecut.drug_bid.repository.UserRepository;
import com.ecut.drug_bid.util.JwtUtil;
import com.ecut.drug_bid.util.PasswordUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final PasswordUtil passwordUtil;
    private final JwtUtil jwtUtil;

    // 注册
    @Transactional
    public AuthResponse register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (userRepository.findByUsername(request.getUsername()).isPresent()) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordUtil.encode(request.getPassword()));
        user.setOrgName(request.getOrgName());
        user.setPhone(request.getPhone());
        user.setUserType(UserType.valueOf(request.getUserType().toUpperCase()));
        user.setStatus(1);

        user = userRepository.save(user);

        // 生成 Token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getUserType().name());

        return new AuthResponse(
            token,
            user.getId(),
            user.getUsername(),
            user.getUserType().name(),
            user.getOrgName()
        );
    }

    // 登录
    public AuthResponse login(LoginRequest request) {
        User user = userRepository.findByUsername(request.getUsername())
            .orElseThrow(() -> new RuntimeException("用户名或密码错误"));

        // 验证密码
        if (!passwordUtil.matches(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException("账户已被禁用");
        }

        // 生成 Token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getUserType().name());

        return new AuthResponse(
            token,
            user.getId(),
            user.getUsername(),
            user.getUserType().name(),
            user.getOrgName()
        );
    }

    // 管理员功能：获取所有用户
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 管理员功能：更新用户状态
    @Transactional
    public void updateUserStatus(Long userId, Integer status) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setStatus(status);
        userRepository.save(user);
    }

    // 管理员功能：删除用户
    @Transactional
    public void deleteUser(Long userId) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 不允许删除管理员
        if (user.getUserType() == UserType.ADMIN) {
            throw new RuntimeException("不能删除管理员账号");
        }
        
        userRepository.deleteById(userId);
    }
}